﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using AmazonCommon;
using System.Configuration;
using System.Web.Caching;
using System.Web;



public class PortalHelper
{

    private static Cache WebCache = HttpRuntime.Cache;

    public static List<WebPortal> GetAll()
    {
        List<WebPortal> result = null;
        using (AmazonAdminDBDataContext ctx = new AmazonAdminDBDataContext())
        {
            result = ctx.WebPortals.ToList();
        }
        return result;
    }



    public static WebPortal GetCurrentPortalFromDB(string guidId)
    {
        Guid portalId = new Guid(guidId);
        WebPortal result = null;
        using (AmazonAdminDBDataContext ctx = new AmazonAdminDBDataContext())
        {
            result = ctx.WebPortals.Single(a => a.ID == portalId);
        }
        return result;
    }

    public static PortalPreset GetPortalPresetFromDB(Guid portalId)
    {
        PortalPreset result = null;


        using (AmazonAdminDBDataContext ctx = new AmazonAdminDBDataContext())
        {
            result = ctx.WebPortals.Single(a => a.ID == portalId).PortalPreset;
        }
        return result;
    }

    public static List<AmazonLocale> GetPortalLocalesFromDB(Guid portalPresetId)
    {
        List<AmazonLocale> result = null;
        using (AmazonAdminDBDataContext ctx = new AmazonAdminDBDataContext())
        {
            result = (from locales in ctx.AmazonLocales
                      join presetLocales in ctx.PresetLocales
                          on locales.ID equals presetLocales.LocaleID
                      where presetLocales.PresetID == portalPresetId
                      select locales).ToList();
        }

        return result;
    }

    public static List<SearchIndexByLocale> GetSearchIndexByLocale(Guid localeID)
    {
        List<SearchIndexByLocale> result = null;
        string cacheKey = "GetSearchIndexByLocale" + localeID.ToString();
        result = WebCache[cacheKey] as List<SearchIndexByLocale>;
        if (result == null)
        {
            result = GetSearchIndexByLocaleFromDB(localeID);
            WebCache.Add(cacheKey, result, null, DateTime.MaxValue, new TimeSpan(100, 0, 0), CacheItemPriority.High, null);
        }
        return result;
    }



    public static List<SearchIndexByLocale> GetSearchIndexByLocaleFromDB(Guid localeID)
    {
        List<SearchIndexByLocale> result = null;
        using (AmazonAdminDBDataContext ctx = new AmazonAdminDBDataContext())
        {
            DataLoadOptions dlo = new DataLoadOptions();
            dlo.LoadWith<SearchIndexByLocale>(p => p.SearchIndex);
            ctx.LoadOptions = dlo;
            result = (from searchIndices in ctx.SearchIndexes
                      join indicesByLocale in ctx.SearchIndexByLocales
                          on searchIndices.ID equals indicesByLocale.SearchIndexID
                      where indicesByLocale.LocaleID == localeID
                      &&
                      indicesByLocale.BrowseNodeAmazonID != null
                      orderby searchIndices.IndexName ascending
                      select indicesByLocale).ToList();

            //foreach (var item in query)
            //{
            //    SearchIndex itemToAdd = item;
            //    itemToAdd.SearchIndexByLocales = ctx.SearchIndexByLocales.Select(a=>a.SearchIndexID==;
            //    result.Add(itemToAdd);
            //}
        }
        return result;
    }

    public static List<SortValue> GetSortValuesBySearchIndex(Guid searchIndexId, Guid localeID)
    {
        List<SortValue> result = null;
        using (AmazonAdminDBDataContext ctx = new AmazonAdminDBDataContext())
        {
            result = (from sortvalues in ctx.SortValues
                      join sortvaluesBySearchIndex in ctx.SortValueBySearchIndexes
                          on sortvalues.ID equals sortvaluesBySearchIndex.SortValueID
                      where
                          sortvaluesBySearchIndex.LocaleID == localeID && sortvaluesBySearchIndex.SearchIndexID == searchIndexId
                      select sortvalues).ToList();
        }
        return result;
    }

    internal static AmazonAccount GetCurrentAccount()
    {
        AmazonLocale currentLocale = GetCurrentLocale();
        WebPortal currentPortal = GetCurrentPortal();
        string cacheKey = "GetCurrentAccount" + currentLocale.ID.ToString() + currentPortal.ID.ToString();
        AmazonAccount result = WebCache[cacheKey] as AmazonAccount;

        if (result == null)
        {
            result = GetAccountFromDB(currentPortal.ID, currentLocale.ID);
            WebCache.Add(cacheKey, result, null, DateTime.MaxValue, new TimeSpan(100, 0, 0), CacheItemPriority.High, null);
        }

        return result;
    }

    internal static AmazonAccount GetAccountFromDB(Guid portalID, Guid localeID)
    {
        AmazonAccount result = null;
        using (AmazonAdminDBDataContext ctx = new AmazonAdminDBDataContext())
        {
            result = (from accounts in ctx.AmazonAccounts
                      join accountsByLocales in ctx.AmazonAccountByLocales
                      on accounts.ID equals accountsByLocales.AccountID
                      where accountsByLocales.LocaleID == localeID
                      &&
                      accountsByLocales.PortalID == portalID
                      select accounts
                        ).Single();
        }
        return result;
    }

    internal static AmazonLocale GetCurrentLocale()
    {
        WebPortal portal = GetCurrentPortal();
        List<AmazonLocale> locales = PortalHelper.GetPortalLocales(portal.PresetID);
        return locales[0];
    }

    private static List<AmazonLocale> GetPortalLocales(Guid guid)
    {
        List<AmazonLocale> result;
        string cacheKey = "GetPortalLocales" + guid.ToString();
        result = WebCache[cacheKey] as List<AmazonLocale>;
        if (result == null)
        {
            result = GetPortalLocalesFromDB(guid);
            WebCache.Add(cacheKey, result, null, DateTime.MaxValue, new TimeSpan(100, 0, 0), CacheItemPriority.High, null);
        }
        return result;
    }

    public static WebPortal GetCurrentPortalFromConfigAndDB()
    {
        string websiteUrl = HttpContext.Current.Request.Url.Host;
        string portalId;
        if (websiteUrl.Contains("localhost") || websiteUrl.Contains("dotnetsql"))
        {
            portalId = ConfigurationManager.AppSettings.Get("PortalID");
        }
        else
        {
            portalId = GetPortalIdByAuthority(websiteUrl);
        }
        WebPortal portal = GetCurrentPortal(portalId);
        return portal;

    }

    public static WebPortal GetCurrentPortal()
    {
        string cacheKey = "CurrentPortal";
        WebPortal result = WebCache[cacheKey] as WebPortal;
        if (result == null)
        {
            result = GetCurrentPortalFromConfigAndDB();
            WebCache.Add(cacheKey, result, null, DateTime.MaxValue, new TimeSpan(100, 0, 0), CacheItemPriority.High, null);
        }
        return result;
    }

    private static string GetPortalIdByAuthority(string websiteUrl)
    {
        string cacheKey = "GetPortalIdByAuthority" + websiteUrl;
        string result = WebCache[cacheKey] as string;
        if (result == null)
        {
            result = GetPortalIdByAuthorityFromDb(websiteUrl);
            WebCache.Add(cacheKey, result, null, DateTime.MaxValue, new TimeSpan(100, 0, 0), CacheItemPriority.High, null);
        }
        return result;
    }

    private static string GetPortalIdByAuthorityFromDb(string websiteUrl)
    {
        string result = null;
        using (AmazonAdminDBDataContext ctx = new AmazonAdminDBDataContext())
        {
            result = (from portals in ctx.WebPortals
                      where portals.PortalUrl.Contains(websiteUrl)
                      select portals).First().ID.ToString();
        }
        return result;
    }



    private static WebPortal GetCurrentPortal(string portalId)
    {
        string cacheKey = portalId;

        WebPortal result = WebCache[cacheKey] as WebPortal;
        if (result == null)
        {
            result = GetCurrentPortalFromDB(portalId);
            WebCache.Add(cacheKey, result, null, DateTime.MaxValue, new TimeSpan(100, 0, 0), CacheItemPriority.High, null);
        }
        return result;

    }

    public static List<SortValue> GetSortValuesBySearchIndex(string category)
    {

        string cacheKey = "GetSortValuesBySearchIndex" + category;
        List<SortValue> result = WebCache[cacheKey] as List<SortValue>;
        if (result == null)
        {
            result = GetSortValuesBySearchIndexFromDB(category);
            WebCache.Add(cacheKey, result, null, DateTime.MaxValue, new TimeSpan(100, 0, 0), CacheItemPriority.High, null);
        }
        return result;
    }

    public static List<SortValue> GetSortValuesBySearchIndexFromDB(string category)
    {
        List<SortValue> result = null;
        using (AmazonAdminDBDataContext ctx = new AmazonAdminDBDataContext())
        {
            result = (from sortValues in ctx.SortValues
                      join sortValuesbySearchIndex in ctx.SortValueBySearchIndexes
                      on sortValues.ID equals sortValuesbySearchIndex.SortValueID
                      where sortValuesbySearchIndex.SearchIndex.IndexName == category
                      select sortValues).ToList();
        }
        return result;
    }


}

